<template>
  <div class="fileContent">
    <label :class="[disabled && 'notAllowed' ]">
      <slot></slot>
      <input
        ref="inputFile"
        class="fileClass"
        @change="handleReadFile"
        v-bind="$props"
        type="file"
        :accept="accept"
      />
    </label>
  </div>
</template>
<script>
export default {
  props: {
    autoComplete: {
      type: String,
      default: 'off',
    },
    disabled: { type: Boolean, default: false },
    accept: { type: [String, Array], default: () => ['image/*'] },
    maxSize: { type: Number, default: 999 },
    name: { type: String, default: '' },
    index: { type: Number, default: 0 },
  },
  methods: {
    async handleReadFile(e) {
      var file = e.target.files || e.dataTransfer.files
      if (file[0]) {
        if (file[0].size / 1024 / 1024 > this.maxSize) {
          this.$emit('handleReadFile', {
            message: `文件大小超过${this.maxSize}M`
          })
        } else {
          var reader = new FileReader()
          await reader.readAsDataURL(file[0])
          reader.onload = (e) => {
            console.log(e)
            this.$emit('handleReadFile', {
              ...this.$props,
              file: file[0],
              size: file[0].size,
              result: e.target.result,
              event: e,
              message: ''
            })
            this.$refs.inputFile.value = ''
          }
        }
      }
    },
    getFile() {
      console.log('get file')
      this.$refs.inputFile.click()
    },
  },
}
</script>
<style scoped>
/* .fileContent input[type='file']::-webkit-file-upload-button {
  cursor: pointer;
} */
.fileContent label {
  cursor: pointer;
}
.notAllowed {
  cursor: not-allowed !important;
  opacity: 0.5;
}
.fileContent .fileClass {
  display: none;
  cursor: pointer;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
}
</style>